package com.android.inestpin.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.inestpin.model.group.MainSearchSortData;
import com.android.inestpin.R;
import com.android.inestpin.SearchActivity;
import com.android.inestpin.activity.MainTab;
import com.android.inestpin.cache.DiskLruCacheHelper;
import com.android.inestpin.model.group.MainSearchSortDataCallback;
import com.android.inestpin.model.group.MainSearchSortSection;
import com.android.inestpin.utils.ConstantsUrl;
import com.android.inestpin.utils.HttpUtils;
import com.android.inestpin.utils.MyLog;
import com.android.inestpin.utils.ObjectUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseSectionQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 搜索页
 */
public class Fragment4 extends Fragment {
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;

    private FragmentActivity mcontext;
    private View view;
    private TextView toolsTextViews[];
    private View views[];
    private int indexs[];
    private LayoutInflater inflater;
    private ScrollView scrollView;
    private int scrllViewWidth = 0, scrollViewMiddle = 0;
    private RecyclerView shop_pager;
    private boolean networkConnected;
    private List<MainSearchSortData.DataBean> listleftdata = new ArrayList<>();
    private List<MainSearchSortSection> listRightdata = new ArrayList<>();
    private AdaptList adapter;
    private StaggeredGridLayoutManager gManager;
    private DiskLruCacheHelper helper;

    public Fragment4() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment4, container, false);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        ButterKnife.bind(this, view);
        try {
            helper = new DiskLruCacheHelper(mcontext);
        } catch (IOException e) {
            e.printStackTrace();
        }
        initUI();
        GetDataListData();
        return view;
    }

    private void initUI() {
        scrollView = (ScrollView) view.findViewById(R.id.tools_list);
        shop_pager = (RecyclerView) view.findViewById(R.id.goods_pager);
        view.findViewById(R.id.search_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("search_type", 0);
                startActivity(intent);
            }
        });
        gManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        shop_pager.setLayoutManager(gManager);
    }

    //获取列表数据
    private void GetDataListData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.SORTLISTDATA;
        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address, null, new MainSearchSortDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainSearchSortData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    if (response.getCode() == 0) {
                        helper.put(ConstantsUrl.CACHE_HOME_SORTDATA_SEARCH, response.toString());
                        listleftdata.clear();
                        List<MainSearchSortData.DataBean> data = response.getData();
                        if (ObjectUtils.listHasData(data)) {
                            listleftdata.addAll(data);
                            for (int i = 0; i < listleftdata.size(); i++) {
                                String headerName = listleftdata.get(i).getCatname();
                                listRightdata.add(new MainSearchSortSection(true, headerName, i, headerName,
                                        listleftdata.get(i).getParentid()));
                                if (listleftdata.get(i).getSub() != null) {
                                    for (int j = 0; j < listleftdata.get(i).getSub().size(); j++) {
                                        List<MainSearchSortData.DataBean.SubBeanX> sub = listleftdata.get(i).getSub();
                                        MainSearchSortData.DataBean.SubBeanX subBeanX = sub.get(j);
                                        MainSearchSortSection sortSection = new MainSearchSortSection(subBeanX, j);
                                        sortSection.setCatname(headerName);
                                        listRightdata.add(sortSection);
                                    }
                                }
                            }
                            showToolsView();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }

    /**
     * 动态生成显示items中的textview
     */
    private void showToolsView() {
        LinearLayout toolsLayout = (LinearLayout) view.findViewById(R.id.tools);
        toolsTextViews = new TextView[listRightdata.size()];
        views = new View[listRightdata.size()];
        for (int i = 0; i < listRightdata.size(); i++) {
            View view = inflater.inflate(R.layout.head_search_left_data, null);
            view.setId(i);
            TextView textView = (TextView) view.findViewById(R.id.text);
            if (!listRightdata.get(i).isHeader) {
                view.setVisibility(View.GONE);
            } else {
                textView.setText(listRightdata.get(i).getCatname());
            }
            view.setOnClickListener(new toolsItemListener(i));
            toolsLayout.addView(view);
            toolsTextViews[i] = textView;
            views[i] = view;
        }

        adapter = new AdaptList(R.layout.list_pro_type_item, R.layout.head_search_right_data, listRightdata);
        shop_pager.setAdapter(adapter);

        shop_pager.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (adapter.getItemCount() > 0) {
                    int[] ints = new int[3];
                    int[] firstVisibleItemPositions = gManager.findFirstVisibleItemPositions(ints);
                    if (firstVisibleItemPositions[0] == -1) {
                        firstVisibleItemPositions[0] = 0;
                    }
                    MainSearchSortSection info = adapter.getData().get(firstVisibleItemPositions[0]);

                    if (info != null) {
                        int index = info.getIndex();
                        if (index > 0 || (index == 0 && firstVisibleItemPositions[0] == 0)) {
                            changeTextColor(firstVisibleItemPositions[0]);
                            changeTextLocation(firstVisibleItemPositions[0]);
                        }
                    }
                }

            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MainSearchSortSection mySection = listRightdata.get(position);
                Intent intent = new Intent(mcontext, MainTab.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 2);

                if (mySection.isHeader) {
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, (mySection.getIndex()));
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE_SERACH, mySection.getParentid());
                } else {
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, mySection.getCatname());
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, (mySection.getIndex2() + 1));
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE_SERACH, mySection.t.getParentid());
                }
                startActivity(intent);
            }
        });
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
        changeTextColor(0);

    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        GetDataListData();
    }


    class toolsItemListener implements View.OnClickListener {
        private int i;


        public toolsItemListener(int i) {
            this.i = i;

        }

        @Override
        public void onClick(View v) {
            changeTextColor(i);
            changeTextLocation(i);
            gManager.scrollToPositionWithOffset(i, 0);
        }
    }


    /**
     * 改变textView的颜色
     */
    private void changeTextColor(int id) {


        for (int i = 0; i < toolsTextViews.length; i++) {
            if (i != id) {
                toolsTextViews[i].setBackgroundColor(Color.parseColor("#ffffff"));
                toolsTextViews[i].setTextColor(Color.parseColor("#333333"));
            }
        }
        toolsTextViews[id].setBackgroundColor(Color.parseColor("#eeeeee"));
        toolsTextViews[id].setTextColor(Color.parseColor("#FF2741"));
    }


    /**
     * 改变栏目位置
     */
    private void changeTextLocation(int clickPosition) {

        int x = (views[clickPosition].getTop() - getScrollViewMiddle() + (getViewheight(views[clickPosition]) / 2));
        scrollView.smoothScrollTo(0, x);
    }

    /**
     * 返回scrollview的中间位置
     */
    private int getScrollViewMiddle() {
        if (scrollViewMiddle == 0)
            scrollViewMiddle = getScrollViewheight() / 2;
        return scrollViewMiddle;
    }

    /**
     * 返回ScrollView的宽度
     */
    private int getScrollViewheight() {
        if (scrllViewWidth == 0)
            scrllViewWidth = scrollView.getBottom() - scrollView.getTop();
        return scrllViewWidth;
    }

    /**
     * 返回view的宽度
     */
    private int getViewheight(View view) {
        return view.getBottom() - view.getTop();
    }

    private class AdaptList extends BaseSectionQuickAdapter<MainSearchSortSection, BaseViewHolder> {


        public AdaptList(int layoutResId, int sectionHeadResId, List<MainSearchSortSection> data) {
            super(layoutResId, sectionHeadResId, data);
        }

        @Override
        protected void convertHead(BaseViewHolder helper, MainSearchSortSection item) {
            helper.setText(R.id.more_title, item.header);
        }

        @Override
        protected void convert(BaseViewHolder helper, MainSearchSortSection item) {
            MainSearchSortData.DataBean.SubBeanX video = item.t;
            helper.setText(R.id.typename, video.getCatname());
            ObjectUtils.photo2(mContext, video.getThumb(), ((ImageView) helper.getView(R.id.typeicon)));
        }
    }

}
